function formatNumber (n) {
  const str = n.toString()
  return str[1] ? str : `0${str}`
}

export function formatTime (date) {
  console.log(date)

  date = new Date(date * 1)
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()

  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  const t1 = [year, month, day].map(formatNumber).join('/')
  const t2 = [hour, minute, second].map(formatNumber).join(':')

  return `${t1} ${t2}`
}

export function formatDate (date) {
  date = new Date(date * 1)
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()

  const t1 = [year, month, day].map(formatNumber).join('-')
  return t1
}

export async function requestPost (url, body, method) {
  return new Promise((resolve, reject) => {
    wx.request({
      url: url,
      data: body,
      method: method,
      header: {
        'content-type': 'application/json'
      },
      success (res) {
        resolve(res.data)
      },
      fail (ret) {
        reject(ret)
      }
    })
  })
}

export async function wxLogin () {
  return new Promise((resolve, reject) => {
    mpvue.login({
      success (res) {
        resolve(res.code)
      }
    })
  })
}

export async function requestOpenId (code) {
  var data = {
    'jscode': code,
    'pid': mpvue.getStorageSync('pid')
  }
  let res = await requestPost(mpvue.getStorageSync('requestUrl') + '/miniprogram/getUserOpenId', data, 'POST')
  return res
}

export async function getOpenId () {
  console.log('s--token:' + mpvue.getStorageSync('token'))
  var code = await wxLogin()
  await requestOpenId(code).then(function (value) {
    console.log(value)
    if (value.code === 0) {
      mpvue.setStorageSync('openId', value.data.openId)
      mpvue.setStorageSync('userId', value.data.userId)
      mpvue.setStorageSync('token', value.data.token)
    } else {
      wx.showToast({
        title: '网络异常(101)',
        icon: 'none',
        duration: 5000,
        mask: false
      })
    }
    console.log('s1--token:' + mpvue.getStorageSync('token'))
  }, function (value) {
    wx.showToast({
      title: '网络异常(202)',
      icon: 'none',
      duration: 10000,
      mask: false
    })
  })
}

export default {
  formatNumber,
  formatTime,
  formatDate,
  requestPost,
  getOpenId
}
